<?php

namespace App\System\Base\Repositories;

use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Model\BaseAds;
use Illuminate\Support\Facades\Cache;
use Zend\Log\Writer\Db;


class BaseAdsRepository extends Repository
{
    use SinglePattern;

    /*
     * 获取列表 ads;
     */
    public function AdList($type)
    {

        $ads = Cache::remember('AdList' . $type, config('global.resource_expire'), function () use ($type) {
            return BaseAds::where('type', $type)
                ->orderBy('sort', 'ASC')
                ->select('id', 'name', 'link', 'start_time as startTime', 'end_time as endTime', 'image_path as imagePath')
                ->get();
        });
        $data['total'] = count($ads);
        $data['ads'] = $ads->toArray();
        return $data;
    }

    /*
     * 新增、编辑、删除
     * @author Hjj
     */
    public function setData($data)
    {
        if (!$data) {
            return false;
        }
        \DB::beginTransaction();
        if (isset($data['data'])) {
            foreach ($data['data'] as $v) {
                if (isset($v['id'])) {
                    $updata['name'] = $v['name'];
                    $updata['link'] = $v['link'];
                    $updata['image_path'] = $v['image_path'];
                    $updata['sort'] = $v['sort'];
                    $bool = BaseAds::where('id', $v['id'])->update($updata);
                    if (!$bool) {
                        \DB::rollBack();
                        return ['data' => $bool, 'message' => '操作失败'];
                    }
                } else {
                    $updata['name'] = $v['name'];
                    $updata['link'] = $v['link'];
                    $updata['image_path'] = $v['image_path'];
                    $updata['sort'] = $v['sort'];
                    $updata['created_at'] = date('Y-m-d H:i:s', time());
                    $bool = BaseAds::insert($updata);
                    if (!$bool) {
                        \DB::rollBack();
                        return ['data' => $bool, 'message' => '操作失败'];
                    }
                }
            }
        }
        if ($data['delImg']) {
            $bool = BaseAds::whereIn('id', $data['delImg'])->delete();
            if (!$bool) {
                \DB::rollBack();
                return ['data' => $bool, 'message' => '操作失败'];
            }
        }
        \DB::commit();
        return ['data' => 1, 'message' => '操作成功'];
    }

    public function getAds($id)
    {
        $res = BaseAds::where('id', $id)->first();
        return $res;
    }
}